package org.alvin.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MyMqttClientUtil {


    private MqttClient client;

    /**
     * 初始化信息
     *
     * @throws MqttException
     */
    public void init() throws MqttException {
        String broker = "tcp://127.0.0.1:1883";
        String username = "MQTT1";
        String password = "123456";
        String clientid = "maigeruineng_server_mps";

        client = new MqttClient(broker, clientid, new MemoryPersistence());
        // 连接参数
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置用户名和密码
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(60);
        options.setKeepAliveInterval(60);
        // 连接
        client.connect(options);
        if (client.isConnected()) {
            System.out.println("====客户端链接成功======");
            subscribe();
        }
    }

    /**
     * 发布信息
     *
     * @param content
     * @throws MqttException
     */
    public void publish(String content) throws MqttException {
        int qos = 2;
        String topic = "Client/M10824100074/data";
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        client.publish(topic, message);
    }
    /**
     * 订阅消息
     *
     * @throws MqttException
     */
    public void subscribe() throws MqttException {
        int qos = 2;
        String topic = "Server/M10824100074/cmd";
        client.setCallback(new MqttCallback() {

            public void connectionLost(Throwable cause) {
                System.out.println("connectionLost: " + cause.getMessage());
            }

            public void messageArrived(String topic, MqttMessage message) {
                System.out.println("topic: " + topic);
                System.out.println("Qos: " + message.getQos());
                System.out.println("message content: " + new String(message.getPayload()));

            }

            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("deliveryComplete---------" + token.isComplete());
            }

        });
        client.subscribe(topic, qos);
    }

    /**
     * 关闭客户端
     *
     * @throws MqttException
     */
    public void close() throws MqttException {
        client.disconnect();
        client.close();
    }

}
